﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
//using MySql.Data.MySqlClient;

using System.Data;
using System.Data.OleDb;




using Antlr.Runtime;

namespace ANTLR_Question_Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        
        public MainWindow()
        {
            InitializeComponent();
        }
        // mySQL Config
        string server="localhost";
        string database="book";
        //string database = "bookdatabase2";
        string username="root"; 
        string password="";

        const int MAX_DISPLAY_BOOKNAME_LENGTH = 40;
        const int MAX_DISPLAY_BOOKINFO_LENGTH = 47;


        bool connected = false;
        int AllIndex = 0;
        int FilterIndex = 0;
        List<Label> listAllShow = new List<Label>();
        List<string[]> listAllHidden = new List<string[]>();
        List<Label> listFilterShow = new List<Label>();
        List<string[]> listFilterHidden = new List<string[]>();

        //        MySqlConnection SQLconnection = new MySqlConnection();
        OleDbDataAdapter dataAdapter;
        DataSet dataSet;
        DataTable dataTable;

        string connectInfo = ""; 


        void AddLabelToRight(string str, int column)
        {
            int MAX_LABEL_LENGTH = (column==1) ? MAX_DISPLAY_BOOKINFO_LENGTH : MAX_DISPLAY_BOOKNAME_LENGTH;
            if (listAllShow.Count < 20)
            {
                Label lb = new Label();
                listAllShow.Add(lb);
                canvasRight.Children.Add(listAllShow[listAllShow.Count - 1]);

                listAllShow[listAllShow.Count - 1].Content = str.Length < MAX_LABEL_LENGTH ? str : str.Substring(0, MAX_LABEL_LENGTH) + "...";
                listAllShow[listAllShow.Count - 1].ToolTip = str;

                listAllShow[listAllShow.Count - 1].FontFamily = label1.FontFamily;
                listAllShow[listAllShow.Count - 1].FontSize = 16.0 - column * 4;
                Canvas.SetLeft(listAllShow[listAllShow.Count - 1], 10 + 50 * column);
                Canvas.SetTop(listAllShow[listAllShow.Count - 1], listAllShow.Count * 20 - column * 2 + 5);
                listAllShow[listAllShow.Count - 1].Opacity = 0;
                listAllShow[listAllShow.Count - 1].BeginAnimation(Canvas.OpacityProperty, new DoubleAnimation(1.0, new Duration(TimeSpan.FromSeconds(0.2))));
                listAllShow[listAllShow.Count - 1].BeginAnimation(Canvas.TopProperty, new DoubleAnimation(listAllShow.Count * 20 - column * 2, new Duration(TimeSpan.FromSeconds(0.3))));
            }
        }
        void AddLabelToLeft(string str, int column)
        {
            int MAX_LABEL_LENGTH = (column == 1) ? MAX_DISPLAY_BOOKINFO_LENGTH : MAX_DISPLAY_BOOKNAME_LENGTH;
            if (listFilterShow.Count < 20)
            {
                Label lb = new Label();
                listFilterShow.Add(lb);
                canvasLeft.Children.Add(listFilterShow[listFilterShow.Count - 1]);


                listFilterShow[listFilterShow.Count - 1].Content = str.Length < MAX_LABEL_LENGTH ? str : str.Substring(0, MAX_LABEL_LENGTH) + "...";
                listFilterShow[listFilterShow.Count - 1].ToolTip = str;

                listFilterShow[listFilterShow.Count - 1].FontSize = 16.0 - column * 4;
                Canvas.SetLeft(listFilterShow[listFilterShow.Count - 1], 10 + 50 * column);
                Canvas.SetTop(listFilterShow[listFilterShow.Count - 1], listFilterShow.Count * 20 - column * 2 + 5);
                listFilterShow[listFilterShow.Count - 1].Opacity = 0;
                listFilterShow[listFilterShow.Count - 1].BeginAnimation(Canvas.OpacityProperty, new DoubleAnimation(1.0, new Duration(TimeSpan.FromSeconds(0.2))));
                listFilterShow[listFilterShow.Count - 1].BeginAnimation(Canvas.TopProperty, new DoubleAnimation(listFilterShow.Count * 20 - column * 2, new Duration(TimeSpan.FromSeconds(0.3))));
            }
        }

        /*
        void executeMySQL(string command)
        {
            MySqlConnection SQLconnection = new MySqlConnection(connectInfo);
            SQLconnection.Open();
            MySqlCommand SQLcommand = SQLconnection.CreateCommand();
            SQLcommand.CommandText = command;
            MySqlDataReader SQLreader = SQLcommand.ExecuteReader();
            listFilterHidden.Clear();
            while (SQLreader.Read())
            {
                string[] row = new string[SQLreader.FieldCount];
                for (int i = 0; i < SQLreader.FieldCount; i++)
                    row [i] =  SQLreader.GetValue(i).ToString();
                listFilterHidden.Add(row);
            }
            FilterIndex = 0;
            UpdatelistFilterShow(0);
            SQLconnection.Close();
            
        }
        */


        List<string[]> executeMySQL(string command)
        {
            string path = "new.mdb";
            try
            {
                List<string[]> tempList = new List<string[]>();
                dataAdapter = new OleDbDataAdapter(command, "provider=Microsoft.JET.OLEDB.4.0;data source = " + path);
                dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "Sach");
                dataTable = dataSet.Tables[0];

                listFilterHidden.Clear();

                string[] temp = new string[] { "ten_sach", "tac_gia", "NXB", "nam", "lang" };
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    
                    string[] row = new string[5];
                    for (int i = 0; i < 5; i++)
                        row[i] =dataRow[temp[i]].ToString().Trim();

                    listFilterHidden.Add(row);
                    tempList.Add(row);
                }
                return tempList;
            }
            catch
            {
                return null;

            }
        }

        void openconnectMySql()
        {
            try
            {
                dataAdapter = new OleDbDataAdapter("select * from book", "provider=Microsoft.JET.OLEDB.4.0;data source = " + "new.mdb");
                dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "Sach");
                dataTable = dataSet.Tables[0];             
 

                lbStatus.Content = "Kết nối thành công...";
                connected = true;
                txtCommand.Visibility = System.Windows.Visibility.Visible;

            }
            catch
            {
                lbStatus.Content = "Lỗi kết nối. Vui lòng thử lại...";
            }
        }

        void UpdatelistAllShow(int index)
        {
            listAllShow.Clear();
            canvasRight.Children.Clear();
            for (int i = index * 10; i < index * 10 + 10; i++)
            {
                if (i < listAllHidden.Count)
                {
                    AddLabelToRight(listAllHidden[i][0], 0);
                    AddLabelToRight(listAllHidden[i][1] + ", " + listAllHidden[i][2] + " , " + listAllHidden[i][3] + " , " + listAllHidden[i][4], 1);
                }
            }
        }


        void UpdatelistFilterShow(int index)
        {
            listFilterShow.Clear();
            canvasLeft.Children.Clear();
            for (int i = index * 10; i < index * 10 + 10; i++)
            {
                if (i < listFilterHidden.Count)
                {
                    AddLabelToLeft(listFilterHidden[i][0], 0);
                    AddLabelToLeft(listFilterHidden[i][1]+ ", " + listFilterHidden[i][2] + " , " + listFilterHidden[i][3] + " , " + listFilterHidden[i][4], 1);
                }
            }
        }


        void loginMySQL()
        {
            if (connected == false)
            {
                try
                {
                    openconnectMySql();
                    string CommandText = "select * from book";
                    listAllHidden = executeMySQL(CommandText);
                    AllIndex = 0;
                    UpdatelistAllShow(0);
                    btConnect.Content = "Truy vấn";
                }
                catch
                {
                    lbStatus.Content = "Lỗi kết nối. Vui lòng thử lại...";
                }
            }
            else
            {
                // Truy vấn = ANTLR Parsera

                string a = TrimUnicode(txtCommand.Text.Trim().ToLower());
                testLexer lex = new testLexer(new ANTLRStringStream(a));
                testParser par = new testParser(new CommonTokenStream(lex));
                try
                {
                    txtSQL.Visibility = System.Windows.Visibility.Visible;
                    txtSQL.Text = par.query();
                    executeMySQL(txtSQL.Text);
                    UpdatelistFilterShow(0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Câu hỏi sai ngữ pháp, xin vui lòng nhập câu hỏi khác", "Sai ngữ pháp", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    txtSQL.Visibility = System.Windows.Visibility.Hidden;
                    txtSQL.Text = "";
                }
            }
        }

        Dictionary<string, string> TrimUnicodeDict = new Dictionary<string, string>();
        void InitTrimUnicode()
        {
            string[] source = new string[] { "đ", "á", "à", "ả", "ã", "ạ", "ă", "ắ", "ằ", "ẳ", "ẵ", "ặ", "â", "ấ", "ầ", "ẩ", "ẫ", "ậ", "é", "è", "ẻ", "ẽ", "ẹ", "ê", "ế", "ề", "ể", "ễ", "ệ", "í", "ì", "ỉ", "ĩ", "ị", "ó", "ò", "ỏ", "õ", "ọ", "ô", "ố", "ồ", "ổ", "ỗ", "ộ", "ơ", "ớ", "ờ", "ở", "ỡ", "ợ", "ú", "ù", "ủ", "ũ", "ụ", "ư", "ứ", "ừ", "ử", "ữ", "ự", "ý", "ỳ", "ỷ", "ỹ", "ỵ" };
            string[] trimUnicode = new string[] { "d", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "y", "y", "y", "y", "y" };
            for (int i = 0; i < source.Length; i++)
            {
                TrimUnicodeDict.Add(source[i], trimUnicode[i]);
            }
        }

        string TrimUnicode(string str)
        {
            string s = "";
            for (int i = 0; i < str.Length; i++)
            {
                if (TrimUnicodeDict.ContainsKey(str[i].ToString()) == true)
                {
                    s += TrimUnicodeDict[str[i].ToString()];
                }
                else
                {
                    s += str[i];
                }
            }
            return s;
        }

        private void btConnect_Click(object sender, RoutedEventArgs e)
        {
            loginMySQL();
        }        

        

        private void imgAllNext_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (AllIndex < listAllHidden.Count / 10)
                AllIndex++;
            UpdatelistAllShow(AllIndex);

        }

        private void imgAllPrev_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (AllIndex > 0)
                AllIndex--;
            UpdatelistAllShow(AllIndex);
        }

        private void imgFilterNext_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (FilterIndex < listFilterHidden.Count / 10)
                FilterIndex++;
            UpdatelistFilterShow(FilterIndex);
            //MessageBox.Show("clicked");
        }

        private void imgFilterPrev_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (FilterIndex > 0)
                FilterIndex--;
            UpdatelistFilterShow(FilterIndex);
        }

        private void imgClose_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void image2_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState =  System.Windows.WindowState.Minimized;
        }

        private void txtCommand_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitTrimUnicode();
        }

        private void imgAllNext_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

     

      



       
    }
}
